package com.cskaoyan.typehandler;

import com.cskaoyan.util.JsonUtil;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedJdbcTypes;
import org.apache.ibatis.type.MappedTypes;
import org.apache.ibatis.type.TypeHandler;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

// /admin/admin/option
// /admin/admin/list
@MappedTypes(Integer[].class) // bean类中的成员变量的类型
@MappedJdbcTypes(JdbcType.VARCHAR) // 数据库中的字段的类型
public class IntegerArrayTypeHandler implements TypeHandler<Integer[]> {

    @Override
    public void setParameter(PreparedStatement ps, int index, Integer[] parameter, JdbcType jdbcType) throws SQLException {
        String jsonStr = JsonUtil.write(parameter);
        ps.setString(index, jsonStr);
    }
    @Override
    public Integer[] getResult(ResultSet rs, String columnName) throws SQLException {
        String jsonStr = rs.getString(columnName); // 数组的json字符串
        Integer[] array = JsonUtil.read(jsonStr, Integer[].class);
        return array;
    }

    @Override
    public Integer[] getResult(ResultSet rs, int columnIndex) throws SQLException {
        String jsonStr = rs.getString(columnIndex); // 数组的json字符串
        Integer[] array = JsonUtil.read(jsonStr, Integer[].class);
        return array;
    }

    @Override
    public Integer[] getResult(CallableStatement cs, int columnIndex) throws SQLException {
        String jsonStr = cs.getString(columnIndex); // 数组的json字符串
        Integer[] array = JsonUtil.read(jsonStr, Integer[].class);
        return array;
    }
}
